<template>
  <div class="vp-raw w-full page">
    <Grid v-if="showType === 0">
      <template #toolbar-actions>
        <Button type="primary" @click="addNewPlan" style="margin-right: 10px;">新增</Button>
        <Button type="primary" @click="exportData" style="margin-right: 10px;">导出</Button>
        <Button type="primary" @click="showUpload" style="margin-right: 10px;">导入</Button>
      </template>
      <template #toolbar-tools>
        <div style="margin-right:-60px">
          <RadioGroup v-model:value="showType" button-style="solid" style="width:200px">
            <RadioButton :value="1">按明细</RadioButton>
            <RadioButton :value="0">按单</RadioButton>
          </RadioGroup>
        </div>
      </template>
      <template #action="{ row }">
        <Button v-if="row.state == 0" type="link" @click="updatePlanScheduling(row)">生效</Button>
        <Button type="link" @click="viewDetail(row)">查看</Button>
        <Button type="link" @click="editPlan(row)">编辑</Button>
        <Button type="link" @click="deletePlan(row)">删除</Button>
      </template>
    </Grid>
    <Grid2 v-if="showType === 1">
      <template #toolbar-actions>
        <Button type="primary" @click="addNewPlan" style="margin-right: 10px;">新增</Button>
        <Button type="primary" @click="exportData" style="margin-right: 10px;">导出</Button>
        <Button type="primary" @click="showUpload" style="margin-right: 10px;">导入</Button>
      </template>
      <template #toolbar-tools>
        <div style="margin-right:-60px">
          <RadioGroup v-model:value="showType" button-style="solid" style="width:200px">
            <RadioButton :value="1">按明细</RadioButton>
            <RadioButton :value="0">按单</RadioButton>
          </RadioGroup>
        </div>
      </template>
    </Grid2>
    <ElDialog title="导入数据" v-model="uploadDialogVisible" width="40%" @close="closeDialog">
      <div style="display: flex;">
        <el-upload :action="''" ref="upload" class="upload-demo" :auto-upload="false" accept=".csv,.xlsx,.json,.xls" :on-change="handleFileChange" :on-remove="handleFileRemove" :on-exceed="handleExceed" :limit="1"
          style="width: 100%;position: relative;">
          <el-button type="primary">点击上传文件</el-button>
        </el-upload>
        <el-button type="primary" @click="downModel" style="margin-right: 10px;position: absolute;left:150px" :loading="downLoading">下载模版</el-button>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeDialog">取消</el-button>
          <el-button type="primary" @click="confirmImport">确认导入</el-button>
        </div>
      </template>
    </ElDialog>
  </div>
</template>

<script  lang="ts" setup>
import { ref, reactive, onMounted, onUnmounted, nextTick } from "vue";
import { ElMessage,ElMessageBox,ElDialog,ElUpload,ElLoading,ElButton,ElNotification } from "element-plus";
import type { UploadInstance, UploadProps, UploadRawFile } from "element-plus";
import { genFileId } from "element-plus";
import { useRouter, useRoute } from "vue-router";
import { $t } from "@vben/locales";
import { Button, RadioButton, RadioGroup } from "ant-design-vue";
import { cloneDeep } from "@vben/utils";
import { confirm } from '@vben/common-ui';
import TableHeaderFilter from "#/components/tableHeardFilter.vue";
import { useVbenVxeGrid } from "#/adapter/vxe-table";
import type { VxeGridProps, VxeGridListeners } from "#/adapter/vxe-table";
import type { VbenFormProps } from "#/adapter/form";
import { dealVxeGridFilterParameter,getRandom } from "#/utils/tools.ts";
import { deleteProductionPlanApi, getProductionPlanExport, reqLineSchedulingList, getExportExcel,importProductplanExcel} from "#/api/productionPlan";
import { reqLineSchedulingListDetail,reqUpdateLineScheduling,reqDeleteLineScheduling } from "#/api/productionPlan";
const router = useRouter();
const route = useRoute();

const tableHeight = ref(window.innerHeight);
const loadingTable = ref(true);
const uploadDialogVisible = ref(false);
const uploadFiles = ref(null);
const upload = ref<UploadInstance>();

const downLoading = ref(false);
//按单|按明细
const showType = ref(1);
let gridFilterParameter = null;

const gridOptions:VxeGridProps = ref({
  columns: [
    { title: "序号", type: "seq", width: 50 },
    {
      field:"productOrderNumber",
      title:"生产订单号",
      width:"",
      filters: [""],
      filterRender: { name: "customizeFilter",type:"input" }
    },
    { field:"instructionNumber", title:"制令号", width:"" },
    { field:"gridName", title:"生产车间", width:"" },
    { field:"materialCode", title:"物料编码", width:"" },
    { field:"materialName", title:"物料名称", width:"" },
    { field:"planQuantity", title:"计划数量", width:"" },
    { field:"schedulingQuantity", title:"排产数量", width:"" },
    { 
      field:"state",
      title:"状态",
      width:"",
      formatter: ({ cellValue,row,column }) => {
        return cellValue === 0 ? "创建" : cellValue === 1 ? "生效" : cellValue === 2 ? "完成" : "";
      }
    },
    { field:"createdDate", title:"创建时间", width:"" },
    { field:"lastModifiedDate", title:"修改时间", width:"" },
    { fixed: "right", slots: { default: "action" }, title: "操作", visible: true,width:"260" }
  ],
  toolbarConfig: {
    search: false,
    custom: true,
    export: false,
    refresh: true,
    zoom: true
  },
  filterConfig: {
    remote: true
  },
  keepSource: true,
  pagerConfig: {
    enabled: true,
    pageSize: 10,
    pageSizes: [10, 20, 30, 50, 100]
  },
  height: "100%",
  autoResize:true,
  editConfig: {
    trigger: 'click',
    mode: 'cell',
    showStatus: true,
    autoClear: false
  },
  proxyConfig: {
    autoLoad: true,
    ajax: {
      query:({ page }, formValues) => getProductionPlanList({ page,formValues })
    }
  }
});
const gridEvents = {
  filterChange({ filterList }){
    gridFilterParameter = dealVxeGridFilterParameter(filterList);
    showType.value == 0 ? gridApi.query() : gridApi2.query();
  }
}

const gridOptions2:VxeGridProps = ref({
  columns: [
    { title: "序号", type: "seq", width: 50 },
    {
      field:"workOrderNumber",
      title: "排产工单",
      width:"",
      filters: [""],
      filterRender: { name: "customizeFilter",type:"input" }
    },
    {
      field:"state",
      title:"状态",
      width:"",
      formatter:({ cellValue,row,column }) => { return dealStatus(cellValue) }
    },
    { 
      field:"lineSchedulingStartTime",
      title:"排产开始时间",
      width:""
    },
    { 
      field:"lineSchedulingEndTime",
      title:"排产结束时间",
      width:""
    },
    { 
      field:"instructionNumber",
      title:"制令号",
      width:"",
      filters: [""],
      filterRender: { name: "customizeFilter",type:"input" }
    },
    {
      field:"gridName",
      title:"车间名称",
      width:"",
      filters: [""],
      filterRender: { name: "customizeFilter",type:"input" }
    },
    { field:"lineName",title:"产线名称",width:"" },
    { field:"quantity",title:"排产数量",width:"" },
    { 
      field:"materialName",
      title:"物料名称",
      width:"",
      filters: [""],
      filterRender: { name: "customizeFilter",type:"input" }
    },
    { 
      field:"materialCode",
      title:"物料编码",
      width:"",
      filters: [""],
      filterRender: { name: "customizeFilter",type:"input" }
    },
    { field:"craftName",title:"工艺",width:"" },
    { 
      field:"craftProcedures",
      title:"工序",
      width:"",
      formatter:({ cellValue,row,column }) => { return dealProcess(cellValue) }
    },
  ],
  toolbarConfig: {
    search: false,
    custom: true,
    export: false,
    refresh: true,
    zoom: true
  },
  filterConfig: {
    remote: true
  },
  keepSource: true,
  pagerConfig: {
    enabled: true,
    pageSize: 20,
    pageSizes: [10, 20, 30, 50, 100]
  },
  height: "100%",
  autoResize:true,
  editConfig: {
    trigger: 'click',
    mode: 'cell',
    showStatus: true,
    autoClear: false
  },
  proxyConfig: {
    autoLoad: true,
    ajax: {
      query: async ({ page }, formValues) => getProductionPlanListDetail({ page,formValues })
    }
  }
});

const [Grid, gridApi] = useVbenVxeGrid({formOptions:null,gridOptions,gridEvents});
const [Grid2, gridApi2] = useVbenVxeGrid({formOptions:null,gridOptions:gridOptions2,gridEvents});


// 获取生产计划列表
const getProductionPlanList = async (option:any) => {
  try {
    const { page,formValues } = option;
    const params = {
      page: page.currentPage,
      size: page.pageSize
    };
    if(gridFilterParameter) Object.assign(params,gridFilterParameter);
    const response = await reqLineSchedulingList(params);
    return {
      total: response.data.totalElements,
      items: response.data.content
    };
  } catch (error) {
    return { total: 0, items: [] };
  }
};
const getProductionPlanListDetail = async (option:any) => {
  try {
    const { page,formValues } = option;
    const params = {
      page: page.currentPage,
      size: page.pageSize
    };
    if(gridFilterParameter) Object.assign(params,gridFilterParameter);
    const response = await reqLineSchedulingListDetail(params);
    return {
      total: response.data.totalElements,
      items: response.data.content
    };
  } catch (error) {
    return { total: 0, items: [] };
  }
};


// 添加新计划
const addNewPlan = () => {
  router.push({ name: "OmSchedulingListDetails" });
};

const showUpload = () => {
  uploadDialogVisible.value = true;
};

const closeDialog = () => {
  uploadDialogVisible.value = false;
  upload.value!.clearFiles();
  uploadFiles.value = null;
};

//下载模版
const downModel = async () => {
  downLoading.value = true;
  const response = await getExportExcel(); // 调用后端导出 API
  downLoading.value = false;
  if (response.status == 200) {
    const blob = response.data;
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url;
    const timestamp = Date.now();
    a.setAttribute("download", `计划排产导入模版${timestamp}.xls`);
    document.body.append(a);
    a.click();
    a.remove();
    ElMessage.success("计划排产导入模版下载成功！");
  } else {
    ElMessage.error("计划排产导入模版下载失败，请稍后再试！");
  }
};

// 处理文件选择
const handleFileChange = (file) => {
  const fileType = file.name.split(".").pop().toLowerCase();
  const validTypes = ["csv", "xlsx", "json", "xls"];

  if (!validTypes.includes(fileType)) {
    ElMessage.error("不支持的文件格式，请上传 CSV、XLSX 或 JSON 文件");
    return;
  }

  uploadFiles.value = file.raw;
};

// 处理超出文件限制  只允许传一个文件
const handleExceed: UploadProps["onExceed"] = (files) => {
  upload.value!.clearFiles();
  const file = files[0] as UploadRawFile;
  file.uid = genFileId();
  upload.value!.handleStart(file);
  uploadFiles.value = files[0];
};

//移除文件
const handleFileRemove: UploadProps["onRemove"] = (file, file1) => {
  uploadFiles.value = cloneDeep(file1);
};

// 确认导入数据
const confirmImport = async () => {
  if (!uploadFiles.value || uploadFiles.value.length <= 0) {
    ElMessage.warning("请先选择文件");
    return;
  }

  const formData = new FormData();
  // console.error(uploadFiles.value);
  formData.append("file", uploadFiles.value);

  const loading = ElLoading.service({
    lock: true,
    text: "导入中...",
    spinner: "el-icon-loading",
    background: "rgba(0, 0, 0, 0.7)",
  });

  try {
    await importProductplanExcel(formData);
    loading.close();
    await nextTick(() => {
      upload.value!.clearFiles();
      ElMessage.success("数据导入成功");
      uploadDialogVisible.value = false;
      //getProductionPlanList();
    });
  } catch (error) {
    loading.close();
    ElMessage.error(`导入失败: ${error.message || "网络错误"}`);
    console.error("导入失败:", error);
  } finally {
  }
};

// 导出数据
const exportData = async () => {
  try {
    ElMessageBox.confirm("即将导出，是否继续？", "导出确认", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }).then(async () => {
      const response = await getProductionPlanExport(); // 调用后端导出 API
      if (response.status == 200) {
        const blob = response.data;
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement("a");
        a.href = url;
        const timestamp = Date.now();
        a.setAttribute("download", `排产计划${timestamp}.xls`);
        document.body.append(a);
        a.click();
        a.remove();
        ElMessage.success("导出成功！");
      } else {
        ElMessage.error("导出失败，请稍后再试！");
      }
    });
  } catch (error) {
    ElMessage.error(`导出失败：${error.message}`);
  }
};

// 查看详情
const viewDetail = (row:any) => {
 router.push({ name:"OmSchedulingListDetails",query:{ id:row.id,state:2 }});
};
// 编辑计划
const editPlan = (row:any) => {
  //if(row.state > 0) return ElNotification({title:'提示',message:'生效状态下不能进行编辑',type:'warning'});
  router.push({ name:"OmSchedulingListDetails",query:{ id:row.id,state:1 }});
};
//生效
const updatePlanScheduling = (row:any) => {
  confirm({content: '确定将当前行数据置为生效吗?',icon: 'success'}).then(async() => {
    const parameter = { id:row.id,state:1 };
    try {
      await reqUpdateLineScheduling(parameter);
      gridApi.query()
    } catch (error){
      ElNotification({title:'提示',message:'更新失败:' + error.message,type:'error'});
    }
  });
}
// 删除计划
const deletePlan = (row:any) => {
  ElMessageBox.confirm($t("ui.actionMessage.deleting", [row.code]), {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      reqDeleteLineScheduling(row.id).then(() => {
        // 删除成功后显示提示
        ElMessage({
          type: "success",
          message: "删除成功",
        });
        gridApi.query();
      });
    })
    .catch((error) => {
      ElMessage({
        type: "info",
        message: "取消删除",
      });
    });
};

const dealStatus = (status:number|string = 0) => {
  status = Number(status);
  let desc = "";
  switch (status) {
    case 0:
      desc = "创建";
      break;
    case 1:
      desc = "生效";
      break;
    case 2:
      desc = "完成";
      break;
    case 3:
      desc = "关闭";
      break;
    case 4:
      desc = "取消";
      break;
    default:
      desc = "未知";
  }
  return desc;
}

const dealProcess = (procedureList:any = []) => {
  if(!procedureList || !procedureList.length) return;
  const list = procedureList.sort((a,b) => a.sequence - b.sequence);
  const selectedProcessNames = list.map(val => val.procedureName).join('->');
  return selectedProcessNames;
}
</script>

<style lang="scss" scoped>
.page{
  width:100%;
  height:99vh;
}
.production-plan-list {
  padding: 20px;
}

.search-bar {
  margin-bottom: 20px;
}

.action-bar {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
}

.pagination {
  display: flex;
  justify-content: end;
  margin-right: 20px;
  margin-top: 10px;
  width: 100%;
}

.el-table th,
.el-table td {
  border: none; /* 移除所有单元格和表头的边框 */
}
</style>
